
//
//  SLCompleteShipOwnerInformationViewController.m
//  StarLight
//
//  Created by 吴涛 on 16/5/11.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLCompleteShipOwnerInformationViewController.h"
#import "SLShipRangeCollectionViewCell.h"
#import "SLLoginViewModel.h"



@interface SLCompleteShipOwnerInformationViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UICollectionView *rangeCollectionView;

@property (nonatomic, strong) NSArray *dataSource;

@property (nonatomic, strong) UIButton *iconButton;

@property (nonatomic, strong) UITextField *nameTF;

@property (nonatomic, strong) UIButton *certainBtn;

@property (nonatomic, assign) RegisterUserType type;

@property (nonatomic, strong) UITextField *companyTF;

@property (nonatomic, strong) NSSet *rangeSet;

@property (nonatomic, strong) NSMutableArray *rangeArr;

@end

@implementation SLCompleteShipOwnerInformationViewController


- (instancetype)initWithType:(RegisterUserType)type{
  self = [super init];
  if (self) {
    self.type = type;
  }
  return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
  self.view.backgroundColor = [UIColor defeutBackgroudColor];
  

  
  [self setUpTopView];
  
  if (self.type == RegisterUserTypeShip) {
    [self setUpShipMidView];
  }else{
    [self setUpProductView];
  }
  
  [self.view addSubview:self.certainBtn];
  [self.certainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.width.equalTo(self.view);
    make.height.equalTo(@46);
  }];
  

    // Do any additional setup after loading the view.
}

- (void)resignFirst{
  [self.nameTF resignFirstResponder];
}

#pragma mark - setUpUI

- (void)setUpTopView{
  UIView *topView = [UIView new];
  topView.backgroundColor = [UIColor whiteColor];
  [self.view addSubview:topView];
  
  [topView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.equalTo(self.view);
    make.height.equalTo(@117);
    make.top.equalTo(self.mas_topLayoutGuideBottom);
  }];
  
  [topView addSubview:self.iconButton];
  [self.iconButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.mas_equalTo(CGSizeMake(62, 62));
    make.left.top.equalTo(topView).offset(27);
  }];
  
  UILabel *label = [UILabel labelWithFontSize:18 textColor:[UIColor blackColor] text:@"联系人"];
  [topView addSubview:label];
  [label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.iconButton.mas_right).offset(20);
    make.top.equalTo(self.iconButton);
  }];
  
  
  [topView addSubview:self.nameTF];
  [self.nameTF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.iconButton.mas_right).offset(20);
    make.right.equalTo(topView).offset(-60);
    make.top.equalTo(label.mas_bottom).offset(15);
    make.height.equalTo(@31);
  }];
  
  
  UITapGestureRecognizer *tapges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignFirst)];
  [topView addGestureRecognizer:tapges];
}

- (void)setUpShipMidView{
  
  UIView *midView = [UIView new];
  midView.backgroundColor = [UIColor whiteColor];
  [self.view addSubview:midView];
  [midView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.mas_topLayoutGuideBottom).offset(122);
    make.left.width.equalTo(self.view);
    make.height.equalTo(@164);
  }];
  
  UILabel *label = [UILabel labelWithFontSize:18 textColor:[UIColor blackColor] text:@"运输范围"];
  [midView addSubview:label];
  [label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.top.equalTo(midView).offset(27);
  }];
  
  
  [midView addSubview:self.rangeCollectionView];
  [self.rangeCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.equalTo(self.view).offset(-26);
    make.centerX.equalTo(self.view);
    make.top.equalTo(label.mas_bottom).offset(16);
    make.bottom.equalTo(midView).offset(-6);
  }];
  
  
}

- (void)setUpProductView{
  UIView *midView = [UIView new];
  midView.backgroundColor = [UIColor whiteColor];
  [self.view addSubview:midView];
  [midView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.mas_topLayoutGuideBottom).offset(122);
    make.left.width.equalTo(self.view);
    make.height.equalTo(@164);
  }];
  
  UILabel *label = [UILabel labelWithFontSize:18 textColor:[UIColor blackColor] text:@"公司名称"];
  [midView addSubview:label];
  [label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.top.equalTo(midView).offset(27);
  }];

  [midView addSubview:self.companyTF];
  [self.companyTF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(label.mas_bottom).offset(16);
    make.centerX.equalTo(midView);
    make.width.equalTo(midView).offset(-54);
  }];
}

#pragma mark - 检查资料是否完善

- (BOOL)checkUserImformation{
  
  // 如果是 船主， 验证 name 和range
  if (self.type == RegisterUserTypeShip) {
    
    self.rangeSet = [NSSet setWithArray:self.rangeArr];
    return self.rangeSet.count > 0 && self.nameTF.text.length > 1 && self.nameTF.text.length < 7;
    
  }else{
      // 如果是 货主， 验证 name 和compny
    return self.companyTF.text.length > 0 && self.nameTF.text.length > 1 && self.nameTF.text.length < 7;
    
  }

}

#pragma mark - 提交注册

- (void)toCheckUserType{
  
  if ([self checkUserImformation]) {
    
    if (self.type == RegisterUserTypeShip) {
      [self shipOwnerRegister];
    }else{
      [self productOwnerRegister];
    }
    
  }else{
    [SVProgressHUD showErrorWithStatus:@"请完整信息"];
  }
  
  
}

- (void)shipOwnerRegister{
  NSString *userjson = [self retrunJSON];
  
  @weakify(self)
  if ([DEFAULTS objectForKey:@"headPhoto"]) {
    [SLLoginViewModel registerUserWithDataArr:@[userjson,[DEFAULTS objectForKey:@"headPhoto"]] complete:^{
      @strongify(self)
      [self.navigationController popToRootViewControllerAnimated:YES];
    }];
  }else{
    [SLLoginViewModel registerUserWithDataArr:@[userjson] complete:^{
      @strongify(self)
      [self.navigationController popToRootViewControllerAnimated:YES];
    }];
  }
}

- (void)productOwnerRegister{
  NSString *userjson = [self retrunJSON];
  
  @weakify(self)
  
  if ([DEFAULTS objectForKey:@"headPhoto"]) {
    [SLLoginViewModel registerUserWithDataArr:@[userjson,[DEFAULTS objectForKey:@"headPhoto"]] complete:^{
      @strongify(self)
      [self.navigationController popToRootViewControllerAnimated:YES];
    }];
  }else{
    [SLLoginViewModel registerUserWithDataArr:@[userjson] complete:^{
      @strongify(self)
      [self.navigationController popToRootViewControllerAnimated:YES];
    }];
  }
}

- (NSString *)retrunJSON{
  NSMutableDictionary *jsonDic = [NSMutableDictionary new];
  [jsonDic setValue:@"ios" forKey:@"os"];
  [jsonDic setValue:self.nameTF.text forKey:@"name"];
  [jsonDic setValue:self.companyTF.text forKey:@"company"];
  [jsonDic setValue:[DEFAULTS objectForKey:@"phone"] forKey:@"phone"];
  [jsonDic setValue:[DEFAULTS objectForKey:@"code"] forKey:@"code"];
  [jsonDic setValue:[DEFAULTS objectForKey:@"password"] forKey:@"password"];
  [jsonDic setValue:[DEFAULTS objectForKey:@"type"] forKey:@"type"];
  
  if (self.type == RegisterUserTypeShip) {
    NSMutableString *ranges = [NSMutableString string];
    NSMutableArray *arr = [[[self.rangeSet allObjects] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
      NSComparisonResult result = [obj1 compare:obj2];
      return result;
    }] mutableCopy];
    
    for (int i = 0; i < arr.count; i ++) {
      if (i == 0) {
        [ranges appendFormat:@"%@",arr[i]];
      }else{
        [ranges appendFormat:@",%@",arr[i]];
      }
    }
    [jsonDic setValue:ranges forKey:@"rangs"];
  }
  
  return [jsonDic mj_JSONString];
}



#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
  SLShipRangeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  NSDictionary *dic = self.dataSource[indexPath.row];
  [cell configShipRangeWithTitle:dic.allKeys.firstObject];
  return cell;
}


#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  SLShipRangeCollectionViewCell *cell = (SLShipRangeCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
  cell.isTaped = !cell.isTaped;
  
  // 添加如选项列表
  if (cell.isTaped) {
    NSDictionary *dic = self.dataSource[indexPath.row];
    [self.rangeArr addObject:dic.allValues.firstObject];
  }
}



// 更换头像
- (void)toChangeIcon:(UITapGestureRecognizer *)tapGes{
  @weakify(self);
  UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  sheet.title = nil;
  UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  }
  
  UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    @strongify(self)
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
  }];
  UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"本地获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    @strongify(self)
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
  }];
  
  UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
  
  [sheet addAction:action1];
  [sheet addAction:action2];
  [sheet addAction:action3];
  
  [self presentViewController:sheet animated:YES completion:nil];
}

#pragma mark - 照相机代理方法
//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  @weakify(self);
  [picker dismissViewControllerAnimated:YES completion:^{
    @strongify(self)
    // 上传照片
    UIImage *icon = info[UIImagePickerControllerOriginalImage];
    UIImage *iconImage = [self scaleToSize:icon size:CGSizeMake(86, 86)];
    [self.iconButton setImage:icon forState:UIControlStateNormal];
    NSData *imgData = UIImageJPEGRepresentation(iconImage, 0.1);
    
    [DEFAULTS setObject:imgData forKey:@"headPhoto"];
    [DEFAULTS synchronize];
  }];
}



-(UIImage *)scaleToSize:(UIImage *)image size:(CGSize)size
{
  //创建一个bitmap的context
  //并把他设置成当前的context
  UIGraphicsBeginImageContext(size);
  //绘制图片的大小
  [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  //从当前context中创建一个改变大小后的图片
  UIImage *endImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  return endImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - getter

- (UICollectionView *)rangeCollectionView{
  if (!_rangeCollectionView) {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(90, 33);
    layout.minimumLineSpacing = 15;
    layout.minimumInteritemSpacing = 12;
    
    _rangeCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _rangeCollectionView.backgroundColor = [UIColor whiteColor];
    _rangeCollectionView.delegate = self;
    _rangeCollectionView.dataSource = self;
    [_rangeCollectionView registerClass:[SLShipRangeCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    
  }
  return _rangeCollectionView;
}

- (NSArray *)dataSource{
  if (!_dataSource) {
    _dataSource = @[@{@"长江上水":@"1"},@{@"长江下水":@"2"},@{@"苏北运河":@"3"},@{@"苏南运河":@"4"},@{@"江海联运":@"5"},@{@"其它":@"6"}];
  }
  return _dataSource;
}

- (UIButton *)iconButton{
  if (!_iconButton) {
    _iconButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_iconButton setImage:[UIImage imageNamed:@"head"] forState:UIControlStateNormal];
    [_iconButton addTarget:self action:@selector(toChangeIcon:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _iconButton;
}

- (UITextField *)nameTF{
  if (!_nameTF) {
    _nameTF = [UITextField new];
    _nameTF.placeholder = @"联系人(2-7位)";
    _nameTF.backgroundColor = SLGrayColor;
    _nameTF.font = [UIFont systemFontOfSize:24];
  }
  return _nameTF;
}

- (UITextField *)companyTF{
  if (!_companyTF) {
    _companyTF = [UITextField new];
    _companyTF.backgroundColor = SLGrayColor;
    _companyTF.font = [UIFont systemFontOfSize:24];
  }
  return _companyTF;
}

- (UIButton *)certainBtn{
  if (!_certainBtn) {
    _certainBtn = [UIButton buttonWithTitle:@"确定"];
    _certainBtn.backgroundColor = SLYellowColor;
    [_certainBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _certainBtn.titleLabel.font = [UIFont systemFontOfSize:20];

    [_certainBtn addTarget:self action:@selector(toCheckUserType) forControlEvents:UIControlEventTouchUpInside];
  }
  return _certainBtn;
}

- (NSMutableArray *)rangeArr{
  if (!_rangeArr) {
    _rangeArr = [NSMutableArray arrayWithCapacity:1];
  }
  return _rangeArr;
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
